﻿using System;
using System.Net;
using AdAggregator.Parser;
using AdAggregator.SearchData;
using AdAggregator.Util;
using AdAggregator.Website;
using ClothingAggregator.Models.SearchData;
using CsQuery;
using log4net;

namespace ClothingAggregator.Models.Parser
{
    public class AnswearComParser : BaseParser<AnswearComSearchData, MyAdvertisement>
    {
        private const string uriTemplate = "http://answear.com/{0}-k.html{4}/lista,{1},{2},{3}";
        private const int resultsPerPage = 100;
        private readonly ILog log = LogManager.GetLogger(typeof(AnswearComParser));

        public override string Name
        {
            get { return "AnswearCom"; }
        }

        protected override string ComposeUri()
        {
            string attributes = "";
            if (SearchData.Attributes.Count > 0)
            {
                attributes = "/" + String.Join("/", SearchData.Attributes);
            }
            var uri = String.Format(uriTemplate, SearchData.Category,
                                    MapOrderBy(SearchData.OrderBy, SearchData.SortingDirection), resultsPerPage, SearchData.Page, attributes);
            return uri;
        }

        private string MapOrderBy(string orderBy, SortingDirection sortingDirection)
        {
            if (orderBy == "Price")
            {
                return "price_" + sortingDirection.ToString().ToLower();
            }

            return "new";

        }

        protected override IParseResult<MyAdvertisement> ParseResponse(HttpWebResponse response, IAdvertisementSource<MyAdvertisement> website)
        {
            var parseResult = new ParseResult<MyAdvertisement>();
            var dom = CQ.Create(response.GetResponseStream());

            var allAvailable = dom["#primary .pagination .pagRowsNb"].First().Text().ToNullableLong();
            parseResult.AllAvailable = allAvailable ?? 0;
            var products = dom["#products .product"];
            foreach (var element in products)
            {
                var myAd = new MyAdvertisement();
                try
                {
                    var product = CQ.Create(element);
                    var title = product["h4"].Text();
                    if (title.ToLower() == "karta podarunkowa") continue;
                    var link = "http://answear.com" + product["h4 a"].Attr("href");
                    var imgs = product["a.picture img.first"].Attr("src");
                    var price = product["dl dd.pricePromo"].Length > 0
                                    ? product["dl dd.pricePromo"].Text()
                                    : product["dl dd.priceReg"].Text();
                    if (price == String.Empty)
                    {
                        price = product["dl dd.priceNew"].Length > 0
                                    ? product["dl dd.priceNew"].Text()
                                    : product["dl dd.priceOld"].Text();
                    }

                    var priceNum = price.RemoveLastAtTheEnd(" ").RemoveFirstAtTheBeginning(" ")
                        .Replace(',', '.').ToNullableDecimal();
                    myAd.AdSource = Name;
                    myAd.Title = title;
                    myAd.Link = link;
                    myAd.Photo = imgs;
                    myAd.Price = priceNum;
                    myAd.Source = website;
                    myAd.SourceString = website.GetType().Name;
                    parseResult.Results.Add(myAd);
                }
                catch (Exception ex)
                {
                    log.Debug(String.Format("{0}: exception while parsing [{1}]", GetType().Name, myAd.Link), ex);
                }
            }
            return parseResult;
        }

        public override MyAdvertisement ParseSingleAd(string adUrl, IAdvertisementSource<MyAdvertisement> website)
        {
            var request = WebRequest.Create(adUrl) as HttpWebRequest;
            if (request != null)
            {
                var response = request.GetResponse() as HttpWebResponse;
                var myAd = new MyAdvertisement();
                var dom = CQ.Create(response.GetResponseStream());
                var priceTxt = dom["#descPDWrap"].Find("dd.current strong").Text()
                    .RemoveFirstAtTheEnd("zł").RemoveFirstAtTheBeginning("Teraz:").Replace(",", ".").Trim();
                var price = priceTxt.ToNullableDecimal();
                var title = dom["#descPDWrap"].Find("h1.cufon").Text();
                var img = dom["#picPD"].Find("a.zoom").Attr("href");
                myAd.Price = price;
                myAd.Link = adUrl;
                myAd.Source = website;
                myAd.SourceString = website.GetType().Name;
                myAd.Title = title;
                myAd.Photo = img;
                myAd.AdSource = Name;
                return myAd;
            }
            return null;
        }
    }
}